{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Upload a gist via the GitHub API\n",
    "\n",
    "Our OAuthenticator config has passed GitHub information via environment variables.\n",
    "We can use these to publish gists to GitHub.\n",
    "\n",
    "Get the GitHub username and token from environment variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "gh_user = os.environ['GITHUB_USER']\n",
    "gh_token = os.environ['GITHUB_TOKEN']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a `requests.Session` for holding our oauth token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "s = requests.session()\n",
    "s.headers['Authorization'] = 'token ' + gh_token"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Verify that we have the scopes we expect:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'gist, user:email'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r = s.get('https://api.github.com/user')\n",
    "r.raise_for_status()\n",
    "r.headers['X-OAuth-Scopes']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can make a gist!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created gist: https://gist.github.com/6dd52f63aa0860f3018dec36b3c2d7d5\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "r = s.post('https://api.github.com/gists',\n",
    "    data=json.dumps({\n",
    "        'files': {\n",
    "            'test.md': {\n",
    "                'content': '# JupyterHub gist\\n\\nThis file was created from JupyterHub.',\n",
    "            },\n",
    "        },\n",
    "        'description': 'test uploading a gist from JupyterHub',\n",
    "    }),\n",
    ")\n",
    "r.raise_for_status()\n",
    "print(\"Created gist: %s\" % r.json()['html_url'])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
